-- NewDungeonTypeView
-- 地下城类型选择视图

local NewRareInfoView = require("app.newBag.views.NewRareInfoView")
local NewDungeonTypeRender = import(".renders.NewDungeonTypeRender")
local Armature = app:getClass("Armature")

local firstRewardNodePercent = 40 -- 第一个奖励点所处loadingbar的百分比
local eachRewardNodePercentDiff = 30 -- 每一个奖励点百分比之差

local rewardNum = 3

local fileName = string.getModeName(...)
local ClassRef = class(fileName, app.mvc.ViewBase)

ClassRef.VIEW_ROOT_RES = Res.NewDungeonTypeUi

function ClassRef:init()
	self._ui["Panel/Button_close"]:addClickEventListener(function()
		executeFunc(self._onCloseView)
	end)

	self._ui["Panel/Button_more"]:addClickEventListener(function()
		display.pushToast( L("lua_code_text_458") )
	end)

	self._rareInfoPanel = nil -- 宝物详情UI
	self._dungeonsList = {}

	self._ui.Panel_luck:setVisible(false) -- 好运钥匙先隐藏

	-- 宝箱
	self._bomPanel = self._ui.Panel_bom
	self.boxNode = self._bomPanel:getChildByName("Panel_icon")
	self.boxLoadingBar = self._bomPanel:findChild("bar/LoadingBar")
	self.boxExpNode = self._bomPanel:getChildByName("exp")
	self._boxIcon = self._bomPanel:findChild("Panel_icon/icon")
	display.uiAddClick(self._boxIcon, function()
		if self.haveNum and self.haveNum > 0 then --预览宝箱
			executeFunc(self._onOperate, "dungeonsType_previewBoxReward")
		else -- 宝箱tips
			local dataTemp = GD:queryRestrictedRewardShowById(102)
			self:_showRareInfo(dataTemp, self._boxIcon)
		end
	end)
end

-- 检查是否触发了引导
function ClassRef:checkGuide()
    local funcId = Constant.FUNC_TYPE_DUNGEONS
    local params = {
        scene = funcId,
        sceneSelf = self,
        getFunc = self.getGuideNodeFunc,
        nextFunc = self.checkGuide
    }
    EM:notify("checkGuide", params)
end
-- 获取引导node
function ClassRef:getGuideNodeFunc(id)
    if id == 139 then
        return self._dungeonsList[1]:getChildByName("Panel")
    end
end

-- 初始化玩法
-- confs teamTarget_surface 表配置list
-- openLvDict 开放等级dict
function ClassRef:initTypeList(confs, openLvDict)
	for i,conf in ipairs(confs) do
		local id = tonumber(conf.ID)
        local render = NewDungeonTypeRender.create(self._ui["node_" .. i])
        render:onBtnClick(self._onOperate)
        render:setType(Enums.TeamTargetType.Dungeon, openLvDict[id])
        render:setData(conf)
        table.insert(self._dungeonsList, render)
    end

    --self:_initTopLuckInfo()
	-- self:_initRewardStatus()
	self:refreshDungeonBoxInfo()

    self:checkGuide()
end

-- 初始化上方宝物信息 (pwrd未使用)
function ClassRef:_initTopLuckInfo()
	local panelTemp = self._ui.Panel_luck
	local dataTemp = GD:queryRestrictedRewardShowById( 101 )

	panelTemp:addTouchEventListener(function(sender, eventType)
		if eventType == ccui.TouchEventType.ended then
			self:_showRareInfo( dataTemp, panelTemp )
		end
	end)

	local _, usedToday = UD.player:getCharmUsedInfo()
	local canUsedToday = tonumber( GD:getSystemPar( "charmdailymaxcostamount" ) ) -- 今日可使用上限
	panelTemp:getChildByName( "num" ):setString( ( canUsedToday - usedToday ) .. "/" .. canUsedToday )
end

-- 初始化奖励按钮操作 (pwrd未使用)
function ClassRef:_initRewardStatus()
	local restrictedreward_showConf = GD:queryRestrictedRewardShowById( 2 )
	local dungeonsRewardInfo = UD:getUserExpCard()
	for i = 1, rewardNum do
		local rewardNode = self._bomPanel:getChildByName( "reward_"..i )
		rewardNode:getTimeline():gotoFrameAndPlay( 0, true )
		local rewardPanel = rewardNode:getChildByName( "Panel" )
		local activeIcon = rewardPanel:getChildByName( "icon_1" )
		local unActiveIcon = rewardPanel:getChildByName( "icon_2" )
		local lockIcon = rewardPanel:getChildByName( "icon_3" )

		-- tips显示需要的经验卡上限直接读表
		local cumulationInfo = tonumber( GD:getSystemPar( "dungeonExpCardLimit" ) ) 
		local dataInfoTemp = {
			name = L(restrictedreward_showConf.name),
			string1 = L(restrictedreward_showConf.string1),
			string3 = L(restrictedreward_showConf.string3),
			string4 = cumulationInfo > 1 and L(restrictedreward_showConf.string4),
		}
		rewardPanel:addTouchEventListener(function(sender, eventType)
			if eventType == ccui.TouchEventType.began then
				if activeIcon:isVisible() then
					return false
				end
			elseif eventType == ccui.TouchEventType.ended or eventType == ccui.TouchEventType.canceled then
				if lockIcon:isVisible() then
					self:_showRareInfo( dataInfoTemp, rewardPanel )
				elseif unActiveIcon:isVisible() then
					self:_showRareInfo( dataInfoTemp, rewardPanel )
				elseif activeIcon:isVisible() then
					executeFunc(self._onOperate, "dungeonsType_previewReward" , i)
				end
			end
		end)
	end
end

------------------------ 宝箱/动画 start ---------------------
-- 展示上方宝物具体信息
function ClassRef:_showRareInfo( dataTemp, triggerNode )
	if self._rareInfoPanel then
		self._rareInfoPanel:setData( dataTemp )
	else
		self._rareInfoPanel = NewRareInfoView.create()
		self._rareInfoPanel:setData( dataTemp )
		self._ui["Panel"]:addChild( self._rareInfoPanel )

		-- 点击空白区域关闭
		display.nodeRemoveForNotHit(self._rareInfoPanel, function()
			if self._rareInfoPanel then
				self._rareInfoPanel:removeFromParent()
				self._rareInfoPanel = nil
			end
		end)
	end

	local triggerNodeBoundingBox = triggerNode:getBoundingBox()
	local worldPosTemp = triggerNode:getParent():convertToWorldSpace( cc.p( triggerNodeBoundingBox.x, triggerNodeBoundingBox.y ) )
	triggerNodeBoundingBox.x = worldPosTemp.x
	triggerNodeBoundingBox.y = worldPosTemp.y
	display.adjustNodePos( triggerNodeBoundingBox, self._rareInfoPanel )
end

-- 宝箱信息
function ClassRef:refreshDungeonBoxInfo()
	self.haveNum = UD:getDungeonLuckBox()
	self.curPoint = UD:getDungeonsPoint()
	self.maxPoint = UD:getLuckBoxLevelUpPoint(Enums.BoxType.dungeon)
	self._curPointCount = self.curPoint + self.haveNum * self.maxPoint
	if UD:hasDungeonLuckBoxCache() then -- 有宝箱数变化播放动画
		self:playBoxAction()
		UD:clearLuckBoxCacheByKey(Enums.lootType.dungeonLuckBox) -- 取到缓存数据后要清掉
		UD:clearLuckBoxCacheByKey(Enums.lootType.dungeonPoint)
	else
		if UD:onlyDungeonLuckBoxChange() then
			UD:clearLuckBoxCacheByKey(Enums.lootType.dungeonLuckBox)
			self:performWithDelay(function()
				self:_playBoxArmature()
			end, 0.05)
		end
		self:_refreshBoxInfo()
	end
end

-- 初始化宝箱动画
local boxNum = 0
local boxNumCache = 0
local playTimes = -1
local barStart = 0
local barEnd = 0
local startPer = 0
local endPer = 0
local per = 2
function ClassRef:playBoxAction()
	local pointCountCache = UD:getDungeonPointCache()
	local isBoxChange = pointCountCache and pointCountCache ~= self._curPointCount
	if isBoxChange then
		boxNum = math.floor(pointCountCache / self.maxPoint)
		boxNumCache = boxNum
		playTimes = self.haveNum - boxNum
		barStart = pointCountCache % self.maxPoint
		barEnd = playTimes > 0 and self.maxPoint or (barStart + self._curPointCount - pointCountCache)
		startPer = math.ceil(barStart * 100 / self.maxPoint)
		endPer = math.ceil(barEnd * 100 / self.maxPoint)

		self:_refreshBoxInfo(boxNum, barStart)
		self:playBoxBarAni()
	else
		self:_refreshBoxInfo()
	end
end

-- 播放经验条动画
function ClassRef:playBoxBarAni()
	self.boxLoadingBar:schedule(function()
		startPer = math.min(startPer + per, endPer)
		if playTimes < 0 then
			self.boxLoadingBar:stopAllActions()
		else
			if startPer == endPer then
				-- 达到最大值，修改宝箱个数
				boxNum = math.min(boxNum + 1, self.haveNum)
				playTimes = playTimes - 1
				barStart = playTimes < 0 and self.curPoint or 0
				barEnd = playTimes <= 0 and self.curPoint or self.maxPoint
				startPer = math.ceil(barStart * 100 / self.maxPoint)
				endPer = math.ceil(barEnd * 100 / self.maxPoint)
				self:_refreshBoxInfo(boxNum, barStart)
				if boxNumCache ~= boxNum then
					self:_playBoxArmature()
					boxNumCache = boxNum
				end
			else
				self.boxLoadingBar:setPercent(startPer)
				local point = math.floor(startPer / 100 * self.maxPoint)
				self.boxExpNode:setString(table.concat({point, "/", self.maxPoint}))
			end
		end
	end, 0.05)
end

-- 播放宝箱特效
function ClassRef:_playBoxArmature()
	if not self._inArmature then
		local params = {
			armatureName = "shaizibengchu",
			path = Res.ChessRollInEfcPath
		}
		local armature = Armature.create(params)
		local posX, posY = self.boxNode:getChildByName("Node_ani"):getPosition()
		self.boxNode:addChild(armature)
		armature:setPosition(posX, posY)
		armature:setScale(0.3, 0.3)
		self._inArmature = armature
	end
	self._inArmature:setVisible(true)
	self._inArmature:play("shaizibengchu", 1, function(sender)
		sender:setVisible(false)
		self:playBoxBarAni()
	end)
end

function ClassRef:_refreshBoxInfo(boxNum, point)
	if not boxNum then
		boxNum = self.haveNum
	end
	if not point then
		point = self.curPoint
	end
	local maxAccumulateBoxNum = tonumber( GD:getSystemPar( "dungeonBoxAccumulateLimited", 20 ) ) -- 累积的上限
	-- 宝箱个数
	self.boxNode:findChild("bg_num/num"):setString(boxNum)
	self:_refreshBoxNumBg(boxNum > 0)
	self.boxNode:getChildByName("tips_max"):setVisible( maxAccumulateBoxNum <= boxNum )
	self._ui.tlt_2:setString(L("restrictedreward4_surface"))

	if 0 < boxNum then
		self:playAction( nil, true )
	else
		self:pauseAction()
	end
	-- 经验条
	local percent = math.floor(point/self.maxPoint*100)
	self.boxLoadingBar:setPercent(percent)
	self.boxExpNode:setString(table.concat({point, "/", self.maxPoint}))
end

function ClassRef:_refreshBoxNumBg(isShow)
	local remainDayTimes = UD:getLuckBoxRestTimesByType(Enums.BoxType.dungeon) --剩余每日开启次数
	local remainWeekTimes = UD:getLuckBoxWeeklyRestTimesByType(Enums.BoxType.dungeon) -- 剩余每周开启次数
	local redBg = self.boxNode:findChild("bg_num/bg")
    local blackBg = self.boxNode:findChild("bg_num/bg_1")
    if isShow then
        if remainDayTimes > 0 and remainWeekTimes > 0 then
            redBg:setVisible(true)
            blackBg:setVisible(false)
        else
            redBg:setVisible(false)
            blackBg:setVisible(true)
        end
	end
	self.boxNode:getChildByName("bg_num"):setVisible(isShow)
	self.boxNode:getChildByName("mask"):setVisible(not isShow)
	self.boxNode:getChildByName("lock"):setVisible(not isShow)
end
------------------------ 宝箱/动画 end ---------------------

-- 刷新奖励状态 (pwrd未使用)
function ClassRef:refreshRewardStatus()
	-- 奖励达成条件
	for i = 1, rewardNum do
		local rewardNode = self._bomPanel:getChildByName( "reward_"..i )
		rewardNode:findChild( "Panel/num_1" ):setString( i )
	end

	-- 奖励 累积/领取 状态
	local dungeonsRewardInfo = UD:getUserExpCard() -- 地下城宝箱获取详情
	if dungeonsRewardInfo then -- 有数据？
		local realPoint = dungeonsRewardInfo:getRealValidPoint()
		self._bomPanel:getChildByName( "num" ):setString( realPoint )

		local percent = nil
		if 0 == realPoint then
			percent = 0
		elseif 1 == realPoint then
			percent = firstRewardNodePercent
		else
			percent = firstRewardNodePercent + eachRewardNodePercentDiff * ( realPoint - 1 )
		end
		self._bomPanel:findChild( "bar_1/LoadingBar" ):setPercent( percent )

		for i = 1, rewardNum do
			local rewardNode = self._bomPanel:getChildByName( "reward_"..i )
			local rewardPanel = rewardNode:getChildByName( "Panel" )
			local rewardStatusText = rewardPanel:getChildByName( "Text" )
			local activeIcon = rewardPanel:getChildByName( "icon_1" )
			local unActiveIcon = rewardPanel:getChildByName( "icon_2" )
			local lockIcon = rewardPanel:getChildByName( "icon_3" )
			local accumulateRewardNumBg = rewardPanel:getChildByName( "bg_num2" )
			local blackBg = rewardPanel:getChildByName("bg_num2")
			local redBg = rewardPanel:getChildByName("bg_num3")
			local accumulateRewardNum = rewardPanel:getChildByName( "num_2" )

			blackBg:setVisible(false)
			redBg:setVisible(false)
			accumulateRewardNum:setVisible(false)

			local activeStatus = dungeonsRewardInfo:getActiveStatusByLevel( i )
			local cumulationInfo = dungeonsRewardInfo:getCumulationInfoByLevel( i )
			if activeStatus then -- 激活？
				if 0 == cumulationInfo then -- 今日已领取
					rewardStatusText:setString( L("lua_code_text_488") )
					activeIcon:setVisible( false )
					unActiveIcon:setVisible( true )
					lockIcon:setVisible( false )

				else
					rewardStatusText:setString( "" )
					activeIcon:setVisible( true )
					unActiveIcon:setVisible( false )
					lockIcon:setVisible( false )

					redBg:setVisible(true)
					accumulateRewardNum:setVisible( cumulationInfo > 1 )
					accumulateRewardNum:setString( cumulationInfo )
				end
			else
				rewardStatusText:setString( L("lua_code_text_124") )
				activeIcon:setVisible( false )
				unActiveIcon:setVisible( false )
				lockIcon:setVisible( true )

				blackBg:setVisible(cumulationInfo > 1)
				accumulateRewardNum:setVisible( cumulationInfo > 1 )
				accumulateRewardNum:setString( cumulationInfo or 0 )
			end
		end
	else -- 没有数据、说明此前一次副本都没打过。不会累积奖励，只算一次
		self._bomPanel:getChildByName( "num" ):setString( 0 )
		self._bomPanel:findChild( "bar/LoadingBar" ):setPercent(0)

		for i = 1, rewardNum do
			local rewardNode = self._bomPanel:getChildByName( "reward_"..i )
			local rewardPanel = rewardNode:getChildByName( "Panel" )
			rewardPanel:getChildByName( "Text" ):setString( L("lua_code_text_124") )
			rewardPanel:getChildByName( "bg_num2" ):setVisible( false )
			rewardPanel:getChildByName( "num_2" ):setVisible( false )
		end
	end
end

function ClassRef:onOperate(cb)
	self._onOperate = cb
end

function ClassRef:remove()
end

return ClassRef
